// 使用 require 避免模块解析问题
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 状态
  const userInfo = ref(null)
  const token = ref('')
  const isLogin = ref(false)
  const permissions = ref([])

  // 计算属性 (getters)
  const isAdmin = computed(() => {
    return userInfo.value?.role === 'admin'
  })

  const username = computed(() => {
    return userInfo.value?.name || ''
  })

  const userRole = computed(() => {
    return userInfo.value?.role || 'employee'
  })

  // 方法 (actions)
  const setUserInfo = (info) => {
    userInfo.value = info
    isLogin.value = !!info
  }

  const setToken = (newToken) => {
    token.value = newToken
    // 持久化存储token
    if (newToken) {
      uni.setStorageSync('token', newToken)
    } else {
      uni.removeStorageSync('token')
    }
  }

  const setLoginStatus = (status) => {
    isLogin.value = status
  }

  const setPermissions = (newPermissions) => {
    permissions.value = newPermissions
  }

  const clearUserInfo = () => {
    userInfo.value = null
    token.value = ''
    isLogin.value = false
    permissions.value = []
    // 清除本地存储
    uni.removeStorageSync('token')
    uni.removeStorageSync('userInfo')
  }

  const login = ({ token: newToken, userInfo: info }) => {
    setToken(newToken)
    setUserInfo(info)
    // 持久化用户信息
    uni.setStorageSync('userInfo', info)
  }

  const logout = () => {
    clearUserInfo()
    // 跳转到登录页
    uni.reLaunch({
      url: '/pages/login/login'
    })
  }

  const checkLoginStatus = () => {
    const storedToken = uni.getStorageSync('token')
    const storedUserInfo = uni.getStorageSync('userInfo')
    
    if (storedToken && storedUserInfo) {
      setToken(storedToken)
      setUserInfo(storedUserInfo)
      return true
    }
    return false
  }

  return {
    // 状态
    userInfo,
    token,
    isLogin,
    permissions,
    // 计算属性
    isAdmin,
    username,
    userRole,
    // 方法
    setUserInfo,
    setToken,
    setLoginStatus,
    setPermissions,
    clearUserInfo,
    login,
    logout,
    checkLoginStatus
  }
})